package com.wlt.security;

import com.wlt.pojo.Admin;
import com.wlt.pojo.Permission;
import com.wlt.service.AdminService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证和授权的逻辑
 *
 */
@Service
public class MyUserDetailService implements UserDetailsService
{
    @DubboReference
    private AdminService adminService;
    
    @Override
    public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException
    {
        // 1.认证
        Admin byAdminName = adminService.findByAdminName(username);
        
        if (byAdminName == null)
            throw new UsernameNotFoundException(username);  // 用户名不存在,security会抓住这个异常
        
        // 2.授权，要把自定义的permission类型转换为security类型
        List<Permission> allPermission = adminService.findAllPermission(username);
        List<GrantedAuthority>  grantedAuthorities = new ArrayList<>();
        for  (Permission permission : allPermission)
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
        
        // 3.封装为UserDetails
        UserDetails userDetails = User.withUsername(byAdminName.getUsername())
                                      .password(byAdminName.getPassword())
                                      .authorities(grantedAuthorities)
                                      .build();
        
        // 4.返回封装好的UserDetails对象
        return userDetails;
    }
}
